/**
 * 
 */
package com.ginger.zookeeper;

import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Description: 获取节点数据
 * @author 姜锋
 * @date 2018年8月20日 下午5:04:28
 * @version V1.0
 */
public class ZKGetNodeData implements Watcher {
	final static Logger log = LoggerFactory.getLogger(ZKGetNodeData.class);
	private ZooKeeper zooKeeper = null;
	// 服务端地址
	public static final String connectionString = "www.justginger.top:2181,www.justginger.top:2182,www.justginger.top:2183";
	// session过期时间
	public static final Integer sessionTimeout = 5000;
	private static Stat stat = new Stat();

	public ZKGetNodeData() {
	}
	/**
	 * @Description: TODO(这里用一句话描述这个方法的作用) @author 姜锋 @date 2018年8月20日 下午5:46:30 @param @param
	 *               i @param @return @return CountDownLatch @throws
	 */
	public ZKGetNodeData(String connectionString) {
		try {
			zooKeeper = new ZooKeeper(connectionString, sessionTimeout, new ZKNodeOpteator());
		} catch (Exception e) {
			e.printStackTrace();
			if (zooKeeper != null) {
				try {
					zooKeeper.close();
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
			}
		}
	}

	private static CountDownLatch countDown = new CountDownLatch(1);

	public static void main(String[] args) throws Exception {
		ZKGetNodeData zkServer = new ZKGetNodeData(connectionString);
		/**
		 * 参数: path:节点路径 watch:true或者false, 注册一个watch事件 stat : 状态
		 */
		byte[] resByte = zkServer.getZooKeeper().getData("/ginger", true, stat);
		String result = new String(resByte);
		System.out.println("此次查询结果" + result);
		countDown.await();
	}
	@Override
	public void process(WatchedEvent event) {
		try {
			if (event.getType() == EventType.NodeDataChanged) {
				ZKGetNodeData zkServer = new ZKGetNodeData(connectionString);
				byte[] resByte = zkServer.getZooKeeper().getData("/ginger", false, stat);
				String result = new String(resByte);
				System.out.println("更改后的值" + result);
				System.out.println("更改后的版本号New Version: " + stat.getVersion());
				countDown.countDown();
			} else if (event.getType() == EventType.NodeCreated) {
			} else if (event.getType() == EventType.NodeChildrenChanged) {
			} else if (event.getType() == EventType.NodeDeleted) {
			}
		} catch (KeeperException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	/**
	 * @return zooKeeper
	 */
	public ZooKeeper getZooKeeper() {
		return zooKeeper;
	}
	/**
	 * @param zooKeeper 要设置的 zooKeeper
	 */
	public void setZooKeeper(ZooKeeper zooKeeper) {
		this.zooKeeper = zooKeeper;
	}
}
